<template>
	<view class="content">

		<view class="text-area">
			<button @click="led" style="margin-top: 20px;">找鸡</button>

			<button @click="openLed" style="margin-top: 20px;margin-left: 10px;">点灯</button>
		</view>
		
		<view class="uni-flex uni-column">
		             
		              
		</view>
					
	</view>
</template>

<script>
	export default {
		data() {
			return {
				title: 'Hello',
				list:[],
				curDeviceId:"",
				curServiceId:"",
				curCharacteristicWrite:"",
				curCharacteristicRead:"",
				findok:false
			}
		},
		onLoad() {

		},
		methods: {
			led() {
				var that = this;
				//开启蓝牙
				uni.openBluetoothAdapter({
					success(res) {
						console.log(res)

						if (res.errno == 0) {
							that.search();
						}

					},
					fail: function(res) {


						uni.showToast({
							title: '请先开启蓝牙',
							duration: 2000
						});

					}
				})
			},
			search() {
				var that = this;
				this.list = [];
				//搜索蓝牙
				uni.startBluetoothDevicesDiscovery({
					services: [],
					success(res) {
						console.log(res)
					    that.watchBluetoothFound();
					}
				})
				
				
			

			},
			connectBluetooth(){
				var that = this;
				console.log("找自己的")
				var pname="YSBP0";
				var deviceId ="91:20:23:00:00:02";
				var device = null;
				console.log("ss",this.list.length);
				for(var i=0;i<this.list.length;i++){
					console.log("对比",this.list[i],pname);
					if(this.list[i].name==pname&&this.list[i].deviceId==deviceId){
						device = this.list[i];
						break;
					}
				}
				if(device!=null){
					
						 
				console.log("找到了",device);
				this.findok=true;
				this.curDeviceId = device.deviceId;
				
				
				console.log("deviceid",that.curDeviceId);
			
						uni.createBLEConnection({
				            deviceId: that.curDeviceId,
				            timeout: 5000,
				            success: (res) => {
				                console.log('第三步通过deviceId连接蓝牙设备成功res', res);
				                that.getBluetoothServers()
				            },
				            fail: (err) => {
				                console.log('第三步通过deviceId连接蓝牙设备失败err', err);
				      
				            }
				        });
						
				}
				
			},
			watchBluetoothFound() {
				var that = this;
				this.findok= false;
			    uni.onBluetoothDeviceFound(function(res) {
			   
					
					if(that.findok==false){
						console.log("res",res);
						that.list=  res.devices;
						that.connectBluetooth();
					}
			   
			 
			    })
			},
			stopSearchBluetooth() {
			    uni.stopBluetoothDevicesDiscovery({
			        success: (res) => {
			            console.log('第四步停止搜寻附近的蓝牙外围设备成功res', res);
			        },
			        fail: (err) => {
			            console.log('第四步停止搜寻附近的蓝牙外围设备失败err', err);
			        }
			    })
			},
	
			 getBluetoothServers() {
				 var that =this;
				console.log("获取服务 ",this.curDeviceId);
			    uni.getBLEDeviceServices({
			        deviceId: this.curDeviceId,
			        success(res) {
			            console.log('第五步获取蓝牙设备所有服务成功res', res);
			            //这里取res.services中的哪个，这是硬件产商配置好的，不同产商不同，具体看对接协议
			            if (res.services && res.services.length > 1) {
			                  
			            }
						
						for(var i=0;i<res.services.length;i++){
							if(res.services[i].uuid=="0000FFF0-0000-1000-8000-00805F9B34FB"){
								that.curServiceId = res.services[i].uuid;
								that.getBluetoothCharacteristics()
								break;
							}
						}
						
						
			        },
			        fail(err) {
			            console.log('第五步获取蓝牙设备所有服务失败err', err);
			        
			        }
			    })
			},
			 getBluetoothCharacteristics() {
				 console.log("获取特征值")
				var that =this;
			    uni.getBLEDeviceCharacteristics({
			        deviceId: that.curDeviceId,
			        serviceId: that.curServiceId,
			        success: (res) => {
			            console.log('第六步获取蓝牙设备某个服务中所有特征值成功res', res);
			            that.curCharacteristicWrite = res.characteristics.filter(item => item && item.uuid.includes('FFF5'))[
			                    0].uuid
			            that.curCharacteristicRead = res.characteristics.filter(item => item && item.uuid.includes('FFF5'))[
			                    0].uuid
			            that.notifyBluetoothCharacteristicValueChange()
			        },
			        fail: (err) => {
			            console.log('第六步获取蓝牙设备某个服务中所有特征值失败err', err);
			           
			        }
			    });
			},
			 notifyBluetoothCharacteristicValueChange() {
				  var that = this;
				 console.log("监听",that.curDeviceId,that.curServiceId,that.curCharacteristicRead);
				 
				 this.openLed()
			
			
			},
			openLed(){
				let str = '86830201';
				this.writeBLE(str)
			},
			hexStringToArrayBuffer(str) {
			    // 将16进制转化为ArrayBuffer
			    return new Uint8Array(str.match(/[\da-f]{2}/gi).map(function(h) {
			        return parseInt(h, 16)
			    })).buffer
			},
			 writeBLE(str) {
				 
				
			  
			    this.writeBLECharacter(this.hexStringToArrayBuffer(str));
				
				// uni.closeBLEConnection({
				//   deviceId:this.curDeviceId,
				//   success(res) {
				//     console.log("连接断开",res)
				//   }
				// });
				

			},
			 writeBLECharacter(bufferValue){
				 
				console.log("写入",this.curDeviceId,this.curServiceId,this.curCharacteristicWrite,bufferValue);
				 
			    uni.writeBLECharacteristicValue({
			        deviceId: this.curDeviceId,
			        serviceId: this.curServiceId,
			        characteristicId: this.curCharacteristicWrite,
			        value: bufferValue,
			        success(res) {
			            console.log('第八步（写入）向低功耗蓝牙设备特征值中写入二进制数据成功res', res);
			        },
			        fail(err) {
			            console.log('第八步（写入）向低功耗蓝牙设备特征值中写入二进制数据失败err', err);
			         
			        }
			    })
			}
			
		

		}
	}
</script>

<style>
	.content {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}

	.logo {
		height: 200rpx;
		width: 200rpx;
		margin-top: 200rpx;
		margin-left: auto;
		margin-right: auto;
		margin-bottom: 50rpx;
	}

	.text-area {
		display: flex;
		justify-content: center;
	}

	.title {
		font-size: 36rpx;
		color: #8f8f94;
	}
</style>